﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AioNightly.Model;
using MySql.Data.MySqlClient;

namespace AioNightly.Dao
{
    public class AttachDAO
    {
        private void Read2List(MySqlDataReader reader, List<Attach> list)
        {
            while (reader.Read())
            {
                Attach it = new Attach();
                it.Id = reader.GetInt32(0);
                it.ItemId = reader.GetInt32(1);
                it.Path = reader.GetString(2);
                it.CreateTime = reader.GetString(3);

                list.Add(it);
            }
        }

        public List<Attach> GetAttachByItemId(int itemid)
        {
            DBConnect db = new DBConnect();
            db.OpenConnection();

            List<Attach> list = new List<Attach>();
            string sql = string.Format("select * from attach where itemid={0}", itemid);
            MySqlCommand cmd = new MySqlCommand(sql, db.Conn);
            MySqlDataReader reader = cmd.ExecuteReader();

            Read2List(reader, list);

            if (reader != null)
                reader.Close();

            db.CloseConnection();

            return list;
        }

        public int AddAttach(int itemid, string path, string createTime)
        {
            DBConnect db = new DBConnect();
            db.OpenConnection();

            string sql = string.Format("insert into attach (ItemId, Path, CreateTime) values ({0}, '{1}', '{2}')", itemid, path, createTime);
            MySqlCommand cmd = new MySqlCommand(sql, db.Conn);
            int result = cmd.ExecuteNonQuery();

            return result;
        }
    }
}